// pages/zeroBuy/zeroBuyDetail/zeroBuyDetail.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        zeroBuyId: null,
        zeroBuyInfo: {},
        remainDay: 0,
        remainHour: 0,
        remainMinute: 0,
        remainSecond: 0,
        stopTime: '',
        overTime: false,
        shareClick: false,
        ewmCode: '',
        previewImg: '',
        showShareImg: false,
        showAdv: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // if (options.storeId) {
        //     wx.setStorageSync('storeId', options.storeId)
        //     if (wx.getStorageSync('token')) {
        //         let data = {
        //             store_id: options.storeId
        //         }
        //         common.post("Store/change_user_store", data).then(function(res) {}).catch(function(e) {})
        //     }
        // }
        if (options.userShare) {
            wx.setStorageSync('userShare', options.userShare)
            if (wx.getStorageSync('token')) {
                let data = {
                    belong_refer: options.userShare
                }
                common.post('User/set_belong_refer', data).then(function(res) {}).catch(function(e) {})
            }
        }
        this.setData({
            zeroBuyId: options.zeroBuyId
        })

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        //浏览记录
        let data = {
            type: 4,
            client: 2
        }
        common.post('Userbrowse/add_user_browse', data).then(function(res) {}).catch(function(e) {})
        this.getZeroBuyDetail()
        this.getTime()
        this.time = setInterval(this.getTime, 1000)

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        clearInterval(this.time)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        common.refresh()
        setTimeout(function() {
            wx.stopPullDownRefresh()
        }, 2000)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        const that = this
        let userId = wx.getStorageSync('userId')
        let storeId = wx.getStorageSync('storeId')
        return {
            title: '邀好友助力，看看我的人品好不好？',
            path: '/pages/zeroBuy/zeroBuyDetail/zeroBuyDetail?zeroBuyId=' + that.data.zeroBuyId + '&userShare=' + userId,
            imageUrl: that.data.zeroBuyInfo.goods[0].image_thumb
        }
    },

    myCatchTouch: function() {
        return
    },

    getZeroBuyDetail: function() {
        wx.showLoading({
            title: '加载中'
        })
        const that = this
        let data = {
            activity_user_id: this.data.zeroBuyId
        }
        common.post('Activity/get_activity_user', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                return
            }
            that.setData({
                zeroBuyInfo: res,
                stopTime: res.end_time
            })
            that.getTime()
            that.time = setInterval(that.getTime, 1000)
            that.getEwmCode()
        }).catch(function(e) {})
    },

    getEwmCode: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('storeId'),
            zeroBuyId: this.data.zeroBuyId,
            img: this.data.zeroBuyInfo.goods[0].image_thumb
        }
        common.post('Qrcodes/create_zero_activity', data).then(function(res) {
            that.setData({
                ewmCode: res
            })
        }).catch(function(e) {})
    },

    getTime: function() {
        let today = new Date(),
            h = today.getHours(),
            m = today.getMinutes(),
            s = today.getSeconds()
        let stopTime = new Date(this.data.stopTime.replace(/-/g, '/')),
            stopH = stopTime.getHours(),
            stopM = stopTime.getMinutes(),
            stopS = stopTime.getSeconds()
        let remainTime = stopTime.getTime() - today.getTime()
        if (remainTime < 0) {
            this.setData({
                overTime: true
            })
            clearInterval(this.time)
            return
        }
        let remainDay = parseInt(remainTime / (60 * 60 * 24 * 1000))
        this.setData({
            remainDay: remainDay
        })
        let remainTimeD =
            parseInt(remainTime) -
            parseInt(remainDay * 60 * 60 * 24 * 1000)
        let remainHour = parseInt(remainTimeD / (60 * 60 * 1000))
        this.setData({
            remainHour: remainHour
        })
        let remainTimeH = remainTimeD - remainHour * 60 * 60 * 1000
        let remainMinute = parseInt(remainTimeH / (60 * 1000))
        this.setData({
            remainMinute: remainMinute
        })
        let remainTimeM = remainTimeH - remainMinute * 60 * 1000
        let remainSecond = parseInt(
            (remainTime -
                remainDay * 60 * 60 * 24 * 1000 -
                remainHour * 60 * 60 * 1000 -
                remainMinute * 60 * 1000) /
            1000
        )
        this.setData({
            remainSecond: remainSecond
        })
    },

    goHelp: function(e) {
        console.log(e.detail.formId)
        common.post('User/up_form_id', {
            form_id: e.detail.formId
        }).then(function(res) {}).catch(function(e) {})
        const that = this
        let data = {
            activity_user_id: this.data.zeroBuyInfo.activity_user_id
        }
        common.post('Activity/add_activity_log', data).then(function(res) {
            if (res.code == 204) {
                wx.showModal({
                    title: '提示',
                    content: res.error,
                    showCancel: false,
                    success(res) {}
                })
            } else {
                wx.showModal({
                    title: '提示',
                    content: '成功助力',
                    showCancel: false,
                    success(res) {
                        that.setData({
                            showAdv: true
                        })
                    }
                })
            }
        }).catch(function(e) {})
    },

    goGet: function() {
        wx.showLoading({
            title: '请稍后'
        })
        const that = this
        let data = {
            num: 1,
            goods_id: this.data.zeroBuyInfo.goods[0].goods_id,
            store_id: wx.getStorageSync('storeId'),
            type: 7,
            sku_sn: this.data.zeroBuyInfo.goods[0].goods_sn
        }
        common.post('Cart/add_cart', data).then(function(res) {
            wx.hideLoading()
            wx.setStorageSync('zeroBuyGoodsInfo', that.data.zeroBuyInfo.goods[0])
            wx.setStorageSync('zeroBuyCartId', res.cart_id)
            wx.setStorageSync('activityUserId', that.data.zeroBuyInfo.activity_user_id)
            wx.navigateTo({
                url: '/pages/zeroBuy/orderConfirm/orderConfirm'
            })
        }).catch(function(e) {})
    },

    goRules: function() {
        wx.navigateTo({
            url: '/pages/zeroBuy/rules/rules'
        })
    },

    goShare: function() {
        this.setData({
            shareClick: true
        })
    },

    cancleShare: function() {
        this.setData({
            shareClick: false
        })
    },

    closeAdv: function() {
        this.setData({
            showAdv: false
        })
    },

    imgShare: function() {
        this.setData({
            showShareImg: true,
            shareClick: false
        })
        this.createImg()
    },
    
    h5Share: function(e) {
        let that = this;
        wx.setClipboardData({
            data: "https://yidianyuan.bailingyoupin.com/activity/zeroBuyDetail.html?zeroBuyId=" + that.data.zeroBuyId,
            success: function(res) {
                wx.showToast({
                    title: '复制成功！'
                });
                that.setData({
                    shareClick: false
                })
            }
        });
    },

    closeImgShare: function() {
        this.setData({
            showShareImg: false
        })
    },

    createImg: function() {
        wx.showLoading({
            title: '正在生成图片...',
        })
        const that = this
        const wxGetImageInfo = this.promisify(wx.getImageInfo)
        Promise.all([
            wxGetImageInfo({
                src: 'https://yidianyuan.bailingyoupin.com/static/images/wx_sm/home/shop-zero-buy-share-img.png?t=' + new Date().getTime()
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.zeroBuyInfo.goods[0].image_thumb.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.ewmCode.split(':')[1]
            })

        ]).then(res => {
            const ctx = wx.createCanvasContext('shareCanvas')
            ctx.drawImage(res[0].path, 0, 0, 750, 1234)
            ctx.drawImage(res[1].path, 200, 300, 350, 350)
            ctx.drawImage(res[2].path, 290, 870, 170, 170)
            ctx.setTextAlign('center')
            ctx.setFillStyle('#131313')
            ctx.setFontSize(30)
            ctx.fillText(that.data.zeroBuyInfo.goods[0].goods_name.slice(0, 15), 375, 670)
            if (that.data.zeroBuyInfo.goods[0].goods_name.length > 15) {
                ctx.setTextAlign('center')
                ctx.setFillStyle('#131313')
                ctx.setFontSize(30)
                ctx.fillText(that.data.zeroBuyInfo.goods[0].goods_name.slice(15, 28), 375, 710)
            }
            ctx.setFillStyle('#ffffff')
            ctx.setFontSize(32)
            ctx.fillText('已有' + that.data.zeroBuyInfo.activity.part_num + '人领取', 543, 805)
            ctx.setFillStyle('#d71a09')
            ctx.setFontSize(40)
            ctx.setTextAlign('center')
            ctx.fillText(that.data.zeroBuyInfo.need_num, 500, 208)
            ctx.draw(false, function(e) {
                const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                wxCanvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    x: 0,
                    y: 0,
                    width: 750,
                    height: 1234,
                    destWidth: 750,
                    destHeight: 1234
                }, this).then(res => {
                    wx.hideLoading()
                    that.setData({
                        previewImg: res.tempFilePath
                    })
                })
            })
        })
    },

    downloadImg: function() {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: this.data.previewImg,
            success: function(data) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
                that.closeShare()
            },
            fail: function(err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    wx.showModal({
                        title: '用户未授权',
                        content: '请先开启保存到相册权限，开启后即可保存图片',
                        success(res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(settingdata) {
                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                            wx.saveImageToPhotosAlbum({
                                                filePath: that.data.previewImg,
                                                success(res) {
                                                    wx.showToast({
                                                        title: '保存成功',
                                                        icon: 'success',
                                                        duration: 2000
                                                    })
                                                    that.closeShare()
                                                }
                                            })
                                        } else {
                                            wx.showToast({
                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }
                                })
                            } else if (res.cancel) {
                                wx.showToast({
                                    title: '保存图片失败，请确认开启授权后重新保存图片',
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        }
                    })
                }
            }
        })
    },

    promisify: function(api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },

    circleImg: function(ctx, img, x, y, r) {
        ctx.beginPath()
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },

    goBack: function() {
        if (getCurrentPages().length == 1) {
            wx.switchTab({
                url: '/pages/index/index'
            })
        } else {
            wx.navigateBack({
                delta: 1
            })
        }
    }
})